package com.twoscreen;

import java.util.ArrayList;
import java.util.logging.Logger;

import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class DataCache {
	private static final Logger log = Logger.getLogger("com.twoscreen.DataCache.java");
	private static MemcacheService keycache = MemcacheServiceFactory.getMemcacheService();
	
	/**
	 * Adds an entry into the Memcache service
	 * @param key The key of the data to be stored
	 * @param value The value of data to be stored
	 */
	public static void addToCache(String key, Object value) {
		keycache.put(key, value, Expiration.byDeltaMillis(PlayerScreen.getValidForMiliseconds()));
		log.info("Added to cache");
	}
	
	/**
	 * Attempts to retrieve key from the Memcache if not returns blank array
	 * @param key The key to check the cache for
	 * @return An empty array or the entry from the cache
	 */
	@SuppressWarnings("unchecked")
	public static ArrayList<String> getArrayListFromCache(String key) {
		ArrayList<String> rtn = new ArrayList<String>();
		try {
			if (keycache.contains(key)) {
				Object obj = keycache.get(key);
				if (obj.getClass().equals(ArrayList.class)) {
					rtn = (ArrayList<String>) obj;
				} else {
					log.warning("Class did not match from cache - class: " + obj.getClass());
				}
			}
		} catch (Exception e) {
			log.info("Could not get from cache: " + key);
		}
		return rtn;
	}
	
	/**
	 * Attempts to retrieve key from the Memcache if not returns null String
	 * @param key The key to check the cache for
	 * @return A null String or the entry from the cache
	 */
	public static String getStringFromCache(String key) {
		String rtn = null;
		try {
			if (keycache.contains(key)) {
				Object obj = keycache.get(key);
				if (obj.getClass().equals(String.class)) {
					rtn = obj.toString();
				} else {
					log.warning("Class did not match from cache - class: " + obj.getClass());
				}
			}
		} catch (Exception e) {
			log.info("Could not get from cache: " + key);
		}
		return rtn;
	}

}
